<?php
namespace app\admin\controller;

use app\Request;
use think\facade\View;
use app\repositories\contracts\MenuInterface;

class Menu extends ViewBaseController
{
    public function index()
    {
        return View::fetch();
    }

    /***
     * @param MenuInterface $menu
     * @return \think\response\Json
     * @Author Vee7
     * @Date 2021/12/15
     * @Time 9:20
     * @Description 返回菜单列表的接口
     */
    public function getMenuListJson(Request $request,MenuInterface $menu)
    {
        $page = $request->param('page');
        $limit = $request->param('limit');

        //通过数据库limit查询做分页，由于是先查询再格式化Tree，因此部分子类会不显示
        //$dataList = $menu->getMenuListPage($page,$limit,'sort','desc');

        $menuList = $menu->getMenuList('sort','desc');
        //获取全部数据通过数组做分页，但数据量过大时不推荐使用,若必须采用此办法，建议采用缓存存储第一次查询的数据，此后通过查询缓存进行分页查询
        $dataListTree = $this->getMenuListJsonTree($menuList);
        $dataListTree = array_slice($dataListTree,(($page-1)*$limit),$limit);
        return layuiJson(0,'菜单列表获取成功',$dataListTree,$menu->getMenuListCount());
    }

    /***
     * @param $data
     * @Author Vee7
     * @Date 2021/12/20
     * @Time 16:51
     * @Description 将菜单数据转为树状结构
     */
    public function getMenuListJsonTree($data)
    {
        return treeMenu($data);
    }

    /***
     * @param MenuInterface $menu
     * @return \think\response\Json
     * @Author Vee7
     * @Date 2021/12/15
     * @Time 9:21
     * @Description 删除菜单接口
     */
    public function del(Request $request,MenuInterface $menu)
    {
        $idArray = $request->param('idArray');
        $bool = $menu->delMenuList($idArray);
        if(!$bool)
        {
            $result = layuiJson(1,'删除失败');
            return $result;
        }
        return layuiJson(0,'删除成功',$idArray);
    }

    /***
     * @param Request $request
     * @param MenuInterface $menu
     * @return \think\response\Json
     * @Author Vee7
     * @Date 2021/12/15
     * @Time 10:40
     * @Description 修改指定字段接口
     */
    public function editList(Request $request,MenuInterface $menu)
    {
        $editArray = $request->param();

        $result = $menu->editMenuList($editArray);
        if(!$result)
        {
            $result = layuiJson(1,'修改失败');
            return $result;
        }
        return layuiJson(0,'修改成功',$result);
    }

    /***
     * @Author Vee7
     * @Date 2021/12/15
     * @Time 13:46
     * @Description 添加菜单
     */
    public function add(Request $request,MenuInterface $menu)
    {
        if(!$request->isPost()){
            $allMenuList = $menu->getMenuList();
            $dataListTree = $this->getMenuListJsonTree($allMenuList);
            return View::fetch('',['allMenuList'=>$dataListTree]);
        }

        $addArray = $request->param();
        $result = $menu->addMenuList($addArray);

        return layuiJson(0,'添加成功',$result);
    }
}
